import type { CardItem } from '../types/cardData';
import { generateSnowflakeId } from '../utils/snowflake';

// 获取卡片列表
export async function fetchLocalCards(page: number, pageSize: number): Promise<{
  items: CardItem[];
  hasMore: boolean;
  total: number;
}> {
  const data = await window.electronAPI.loadCards();
  
  // 按卡片创建时间降序排序（最新创建的卡片排在前面）
  const sortedCards = [...data.cards].sort((a, b) => {
    return new Date(b.created).getTime() - new Date(a.created).getTime();
  });
  
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  
  return {
    items: sortedCards.slice(startIndex, endIndex),
    hasMore: endIndex < sortedCards.length,
    total: sortedCards.length
  };
}

// 获取单个卡片
export async function getLocalCard(cardId: string): Promise<CardItem | null> {
  const data = await window.electronAPI.loadCards();
  // 获取所有卡片
  const cards = data.cards;
  // 查找指定ID的卡片
  return cards.find((c: CardItem) => c.id === cardId) || null;
}

// 保存卡片
export async function saveLocalCard(card: Partial<CardItem>): Promise<CardItem> {
  // Generate snowflake ID if this is a new card
  if (!card.id) {
    card.id = generateSnowflakeId();
  }
  
  // Create a clean object to avoid cloning issues
  const sanitizedCard = JSON.parse(JSON.stringify({
    id: card.id,
    title: card.title || '',
    content: card.content || '',
    markdown: card.markdown || '',
    tags: card.tags || [],
    tagColors: card.tagColors || {},
    bucket: card.bucket || '',
    created: card.created || new Date().toISOString(),
    updated: new Date().toISOString(),
    startTime: card.startTime || new Date().toISOString(),
    isStarred: card.isStarred || false
  }));
  
  return await window.electronAPI.saveCard(sanitizedCard);
}

// 删除卡片
export async function deleteLocalCard(cardId: string): Promise<boolean> {
  return await window.electronAPI.deleteCard(cardId);
}

// 批量删除卡片
export async function batchDeleteLocalCards(cardIds: string[]): Promise<{ success: boolean; count: number }> {
  try {
    let successCount = 0;
    
    // 依次删除每个卡片
    for (const cardId of cardIds) {
      const success = await window.electronAPI.deleteCard(cardId);
      if (success) {
        successCount++;
      }
    }
    
    return {
      success: successCount > 0,
      count: successCount
    };
  } catch (error) {
    console.error('批量删除卡片失败:', error);
    return {
      success: false,
      count: 0
    };
  }
}